


var ajax = require("../ajax/ajax");
var mongo = require("../mongo/mongo");

var validator = require("validator");
var moment = require("moment");
var py = require("../comm/py");

function get(req, res, r, c) {
    var para = req.body.para;
    switch (para) {
        case "saveFlow":  //保存用户信息

            saveFlow(req, res).then(r).catch(c);
            break;
        case "getFlowList":
            getFlowList(req, res).then(r).catch(c)
            break;
        case "getFlow":
            getFlow(req, res).then(r).catch(c)
            break;
        default:
    }
}



async function getFlow(req, res) {
    var j = req.body.j;

    if (!j._id) {
        throw '不能没有id'
    }

    var info = await mongo.findOneAsync({
        data: {
            _id: j._id

        },
        db: "uzor",
        collection: "Flow"


    })
    return { info: info }
}


//查询用户列表
async function getFlowList(req, res) {

    var j = req.body.j

    var data = await mongo.findAsync({

        data: j.data,
        limit: 10,
        db: "uzor",
        collection: "Flow",
        sort: { createTime: -1 },
        page: j.page


    })
    return data


}

//保存用户
async function saveFlow(req, res) {

    var j = req.body.j;

    if (!validator.isLength(j.name, { min: 1, max: 100 })) {

        throw "名称长度必须在1到100之间"
    }

    if (!j._id || !j.createTime) {
        j.createTime = moment().utcOffset(-8)._d;
    }
    try {
        j.createTime = moment(j.createTime)._d;
    } catch (e) {

    } finally {

    }

    j.namePy = py.firstLetter(j.name);
    if (j.isDefault) {
        var re = await mongo.upAsync(
            {
                updateFind: {
                    class: j.class

                },
                updateSet: {
                    $set: { isDefault: false }
                },
                multi: true,
                collection: "Flow"
            })

    }
    j.changeTime = moment().utcOffset(-8)._d;

    await mongo.SaveAsync({

        data: j,
        db: "uzor",
        collection: "Flow"


    });


    return

}





module.exports = get;